import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_template/core/http/http.dart';
import 'package:flutter_template/core/utils/privacy.dart';
import 'package:flutter_template/core/utils/toast.dart';
import 'package:flutter_template/core/widget/loading_dialog.dart';
import 'package:flutter_template/core/widget/wrap_gesture_widget.dart';
import 'package:flutter_template/generated/i18n.dart';
import 'package:flutter_template/router/router.dart';
import 'package:flutter_template/utils/provider.dart';
import 'package:flutter_template/utils/sputils.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 响应空白处的焦点的Node
  bool _isShowPassWord = false;
  FocusNode blankNode = FocusNode();
  TextEditingController _unameController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();
  // 区号列表
  List<areaCodeObj> areaList;
  // 默认大陆手机区号+86
  String areaCode = '86';

  @override
  void initState() {
    super.initState();
    if (!SPUtils.isAgreePrivacy()) {
      PrivacyUtils.showPrivacyDialog(context, onAgressCallback: () {
        Navigator.of(context).pop();
        SPUtils.saveIsAgreePrivacy(true);
        ToastUtils.success(I18n.of(context).agreePrivacy);
      });
    }
    areaList = new List();
    areaList
      ..add(areaCodeObj('中国大陆', '86'))
      ..add(areaCodeObj('中国香港', '852'))
      ..add(areaCodeObj('中国澳门', '853'));
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          appBar: AppBar(
            // leading: _leading(context),
            title: Text(I18n.of(context).login),
          ),
          body: GestureDetector(
            onTap: () {
              // 点击空白页面关闭键盘
              closeKeyboard(context);
            },
            child: SingleChildScrollView(
              padding:
                  const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
              child: buildForm(context),
            ),
          ),
        ),
        onWillPop: () async {
          return Future.value(false);
        });
  }

  //构建表单
  Widget buildForm(BuildContext context) {
    return Form(
      key: _formKey, //设置globalKey，用于后面获取FormState
      autovalidate: false,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text("Hi，",
              style: TextStyle(
                  color: Theme.of(context).primaryColor,
                  fontSize: 64,
                  fontWeight: FontWeight.bold)),
          Text("Wellcome to",
              style: TextStyle(
                  color: Theme.of(context).primaryColor,
                  fontSize: 48,
                  fontWeight: FontWeight.bold)),
          // 手机号
          Container(
            margin: EdgeInsets.only(top: 20),
            padding: EdgeInsets.fromLTRB(22, 0, 22, 0),
            decoration: BoxDecoration(
                border: Border.all(color: Colors.black26),
                borderRadius: BorderRadius.circular(6)),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 区号选择器
                _areaCodeSelector(context, areaList),
                Expanded(
                  flex: 1,
                  child: TextFormField(
                      autofocus: false,
                      controller: _unameController,
                      decoration: InputDecoration(
                          hintText: I18n.of(context).loginNameHint,
                          hintStyle: TextStyle(fontSize: 18),
                          border: InputBorder.none),
                      //校验用户名
                      validator: (v) {
                        return v.trim().length > 0
                            ? null
                            : I18n.of(context).loginNameError;
                      }),
                ),
              ],
            ),
          ),
          // 密码
          Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.fromLTRB(22, 0, 22, 0),
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.black26),
                  borderRadius: BorderRadius.circular(6)),
              child: TextFormField(
                  controller: _pwdController,
                  decoration: InputDecoration(
                      hintText: I18n.of(context).passwordHint,
                      hintStyle: TextStyle(fontSize: 18),
                      border: InputBorder.none,
                      suffixIcon: IconButton(
                          icon: Icon(
                            _isShowPassWord
                                ? Icons.visibility
                                : Icons.visibility_off,
                            color: Colors.black,
                          ),
                          onPressed: showPassWord)),
                  obscureText: !_isShowPassWord,
                  //校验密码
                  validator: (v) {
                    return v.trim().length >= 6
                        ? null
                        : I18n.of(context).passwordError;
                  })),
          // 注册会员，忘记密码
          Container(
            margin: EdgeInsets.only(top: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 会员注册
                wrapGesture(
                  child: Text(
                    I18n.of(context).register,
                    style: TextStyle(
                        color: Theme.of(context).primaryColor, fontSize: 18),
                  ),
                  function: () {
                    XRouter.goto(context, '/register');
                  },
                ),
                // 忘记密码
                wrapGesture(
                  child: Text(
                    '${I18n.of(context).forgetPassword}?',
                    style: TextStyle(
                        color: Theme.of(context).primaryColor, fontSize: 18),
                  ),
                  function: () {
                    XRouter.goto(context, '/forgetPass');
                  },
                )
              ],
            ),
          ),

          // 登录按钮
          Padding(
            padding: const EdgeInsets.only(top: 28.0),
            child: Row(
              children: <Widget>[
                Expanded(child: Builder(builder: (context) {
                  return RaisedButton(
                    padding: EdgeInsets.all(15.0),
                    child: Text(I18n.of(context).login),
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    onPressed: () {
                      //由于本widget也是Form的子代widget，所以可以通过下面方式获取FormState
                      if (Form.of(context).validate()) {
                        onSubmit(context);
                      }
                    },
                  );
                })),
              ],
            ),
          )
        ],
      ),
    );
  }

  ///点击控制密码是否显示
  void showPassWord() {
    setState(() {
      _isShowPassWord = !_isShowPassWord;
    });
  }

  void closeKeyboard(BuildContext context) {
    FocusScope.of(context).requestFocus(blankNode);
  }

  //验证通过提交数据
  void onSubmit(BuildContext context) {
    closeKeyboard(context);

    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return LoadingDialog(
            showContent: false,
            backgroundColor: Colors.black38,
            loadingView: SpinKitCircle(color: Colors.white),
          );
        });

    UserProfile userProfile = Provider.of<UserProfile>(context, listen: false);

    XHttp.post("/user/login", {
      "username": _unameController.text,
      "password": _pwdController.text
    }).then((response) {
      Navigator.pop(context);
      if (response['errorCode'] == 0) {
        userProfile.nickName = response['data']['nickname'];
        ToastUtils.toast(I18n.of(context).loginSuccess);
        Navigator.of(context).pushReplacementNamed('/home');
      } else {
        ToastUtils.error(response['errorMsg']);
      }
    }).catchError((onError) {
      Navigator.of(context).pop();
      ToastUtils.error(onError);
    });
  }

  Widget _areaCodeSelector(BuildContext context, List<areaCodeObj> list) {
    List<PopupMenuItem> menuList;
    menuList = list.map((element) {
      return PopupMenuItem(
        value: element.code,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              child: Text('${element.area}'),
            ),
            Container(
              child: Text('${element.code}'),
            )
          ],
        ),
      );
    }).toList();

    return Container(
      child: Row(
        children: [
          Text(
            "+$areaCode",
            style: TextStyle(fontSize: 18),
          ),
          PopupMenuButton(
            icon: Icon(Icons.arrow_drop_down),
            initialValue: areaCode,
            itemBuilder: (context) {
              return menuList;
            },
            onSelected: (value) {
              setState(() {
                areaCode = value;
              });
            },
          )
        ],
      ),
    );
  }
}

class areaCodeObj {
  String code;
  String area;
  areaCodeObj(this.area, this.code);
}
